package server.analytics;

/**
 * This class represents subscriptions from a management client to some
 * events at an analytics server. The client can subscribe with
 * regular-expressions, which are beeing saved as a Hashmap with its unique 
 * subscription-id.
 * 
 * @version 1.0 vom 20.11.2012
 * @author Distributed Group 111 1026312, 1026309
 */

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.regex.PatternSyntaxException;

import model.event.Event;

import client.management.ManagementClientNotifier;

public class SubscriptionImpl extends UnicastRemoteObject implements
		Subscription {

	private static final long serialVersionUID = 2292461989782488842L;
	private static int subscriptionId = 1;
	private ManagementClientNotifier notifier;
	private HashMap<Integer, String> regexes;

	public SubscriptionImpl(ManagementClientNotifier notifier)
			throws RemoteException {
		super();
		this.notifier = notifier;
		this.regexes = new HashMap<Integer, String>();
	}

	/* (non-Javadoc)
	 * 
	 * @see server.analytics.Subscription#addRegex(java.lang.String)
	 */
	@Override
	public int addRegex(String newRegex) {
		try {
			"TEST_STRING".matches(newRegex);
		} catch (PatternSyntaxException e) {
			return -1;
		}
		int id;
		if (regexes.containsValue(newRegex))
			return -1;
		else {
			id = SubscriptionImpl.subscriptionId++;
			regexes.put(id, newRegex);
		}

		return id;

	}

	/* (non-Javadoc)
	 * @see server.analytics.Subscription#removeRegex(int)
	 */
	@Override
	public boolean removeRegex(int subscriptionId) throws RemoteException {
		if (regexes.containsKey(subscriptionId)) {
			regexes.remove(subscriptionId);
			return true;
		}

		return false;
	}
	
	/* (non-Javadoc)
	 * @see server.analytics.Subscription#notificate(model.event.Event)
	 */
	public void notificate(Event event) throws RemoteException {
		for (String regex : this.regexes.values()) {
			if (event.getType().toString().matches(regex)) {
				this.notifier.notificate(event.toString());
				break;
			}
		}
	}
}
